package com.tensquare.spit.controller;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("spit")
public class SpitController {

    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;

    //1.查询所有吐槽列表
    @GetMapping
    public Result findAll(){
        //1.调用服务查询吐槽列表
        List<Spit> spitList= spitService.findAll();
        //2.返回结果
        return new Result(true,StatusCode.OK,"吐槽列表查询成功！",spitList);
    }
    //2.根据id查询吐槽列表
    @GetMapping("{spitId}")
    public Result findByID(@PathVariable String spitId){
        //1.根据id查询吐槽对象
        Spit spit=spitService.findById(spitId);
        //2.返回结果
        return new Result(true,StatusCode.OK,"根据id查询吐槽成功！",spit);
    }
    //3.添加吐槽
    @PostMapping
    public Result insert(@RequestBody Spit spit){
        //1.调用服务添加吐槽
        spitService.insert(spit);
        //2.返回结果
        return new Result(true,StatusCode.OK,"添加吐槽成功！");
    }
    //4.修改吐槽
    @PutMapping("{spitId}")
    public Result update(@PathVariable String spitId,@RequestBody Spit spit){
        //1.将id与吐槽对象进行绑定
        spit.set_id(spitId);
        //2.调用服务进行修改
        spitService.update(spit);
        //3.返回结果
        return new Result(true,StatusCode.OK,"修改吐槽成功！");
    }
    //5.根据id删除吐槽
    @DeleteMapping("{spitId}")
    public Result delete(@PathVariable String spitId){
        //1.调用服务进行删除
        spitService.delete(spitId);
        //2.返回结果
        return new Result(true,StatusCode.OK,"删除吐槽成功！");
    }
    //6.根据父id查询吐槽列表
    @GetMapping("comment/{parentid}/{page}/{size}")
    public Result findByParentId(@PathVariable String parentid,@PathVariable int page,@PathVariable int size){
        //1.调用服务获取分页结果
        PageResult<Spit> pageResult=spitService.findByParentId(parentid,page,size);
        //2.返回结果
        return new Result(true,StatusCode.OK,"根据父Id查询列表成功！",pageResult);
    }
    //7.进行吐槽点赞
    @PutMapping("thumbup/{spitId}")
    public Result thumbup(@PathVariable String spitId){
        //1.模拟一个用户
        String userId="1022";
        //2.根据redis来判断用户是否点赞过
        String flag= (String) redisTemplate.opsForValue().get("thumbup_"+userId+"_"+spitId);
        //3.判断是否为空
        if(StringUtils.isNotBlank(flag)){
            return new Result(false,StatusCode.ERROR,"不能重复点赞！");
        }
        //4.调用服务进行点赞
        spitService.thumbup(spitId);
        //5.用户点赞过，那就设置一个标志
        redisTemplate.opsForValue().set("thumbup_"+userId+"_"+spitId,"1");
        //6.返回结果
        return new Result(true,StatusCode.OK,"点赞成功！");
    }


}
